import Vue from "vue"
import VueRouter from "vue-router"
import pathArr from "@/components/router/pathArr.js"
// 导入需要的组件
import Login from "@/components/MyLogin.vue"
import Home from "@/components/MyHome.vue"

// 导入子组件
import Users from "@/components/menus/MyUsers.vue"
import Orders from "@/components/menus/MyOrders.vue"
import Rights from "@/components/menus/MyRights.vue"
import Settings from "@/components/menus/MySettings.vue"
import Goods from "@/components/menus/MyGoods.vue"
import UserDetail from "@/components/user/MyUserDetail.vue"

Vue.use(VueRouter)

const router = new VueRouter({
    routes: [
        { path: "/", redirect: "/login" },
        // 登录的路由规则
        { path: "/login", component: Login },
        {
            path: "/home",
            component: Home,
            redirect: "/home/users",
            children: [
                { path: "users", component: Users },
                { path: "orders", component: Orders },
                { path: "rights", component: Rights },
                { path: "goods", component: Goods },
                { path: "settings", component: Settings },
                // 用户详情页的路由规则
                { path: "userinfo/:id", component: UserDetail, props: true }
            ]
        }
    ]
})

// 路由的全局前置守卫
router.beforeEach(function(to, from, next) {
    // const pathArr = ['/home', '/home/users']
    if (pathArr.indexOf(to.path) !== -1) {
        const token = localStorage.getItem("token")
        if (token) {
            next()
        } else {
            next("/login")
        }
    } else {
        next()
    }
})

export default router